import {
  ConfigProvider,
  GetProps,
  Tabs as BaseTabs,
  theme,
  TabsProps,
  Divider,
  Typography,
} from 'antd';
import { createStyles } from 'antd-style';
import { PropsWithChildren, ReactNode } from 'react';

export function Tabs(props: GetProps<typeof BaseTabs>) {
  const { items, ...restProps } = props;
  const { token } = theme.useToken();

  return (
    <ConfigProvider
      theme={{
        components: {
          Tabs: {
            verticalItemMargin: '0',
            verticalItemPadding: '0',
            paddingLG: 0,
            controlHeight: 0,
            // lineWidth: 0,
            cardPadding: '0',
            colorBgContainer: token.colorPrimaryBg,
            borderRadiusLG: 0,
            cardGutter: 0,
            itemColor: token.colorTextDescription,
          },
        },
      }}
    >
      <BaseTabs
        renderTabBar={(tabsBarProps, DefaultTabBar) => {
          return (
            <DefaultTabBar {...tabsBarProps} className="mr-px text-tertiary">
              {(node) => (
                <TabWithDividerNode {...node.props} key={node.key}>
                  {node}
                </TabWithDividerNode>
              )}
            </DefaultTabBar>
          );
        }}
        tabPosition="left"
        indicator={{ size: 0 }}
        {...props}
        items={createTabItems({ items })}
      />
    </ConfigProvider>
  );
}

interface TabWithDividerProps extends React.HTMLAttributes<HTMLDivElement> {
  'data-node-key': string;
}
const TabWithDividerNode = ({ className, ...props }: TabWithDividerProps) => {
  const key = props['data-node-key'];
  if (key === dividerKey) {
    return (
      <div className="p-2">
        <Divider className="m-0" />
      </div>
    );
  }
  return props.children;
};
const dividerKey = 'divider';
export const TabDivider = {
  key: dividerKey,
  label: null,
};

function createTabItems({ items }: { items: TabsProps['items'] }) {
  return items?.map(({ icon, label, ...item }) => {
    return {
      ...item,
      label: <TabLabel icon={icon}>{label}</TabLabel>,
    };
  });
}

const useTabLabelStyles = createStyles(({ token, prefixCls }) => ({
  colorBgActive: {
    [`.${prefixCls}-tabs-tab-active &`]: {
      backgroundColor: token.colorPrimaryBg,
    },
  },
}));
function TabLabel({ icon, children }: PropsWithChildren<{ icon?: ReactNode }>) {
  const { styles, cx } = useTabLabelStyles();
  return (
    <div
      className={cx(
        'w-16 h-16 p-2 leading-none text-3xl flex flex-col items-center justify-center',
        styles.colorBgActive,
      )}
    >
      <span>{icon}</span>
      <span className="text-2xs pt-0.5">{children}</span>
    </div>
  );
}
